import org.apache.hadoop.conf.Configuration;
import org.apache.hive.jdbc.HiveDriver;

public class HiveExample {
    public static void main(String[] args) throws Exception {
        // 配置连接参数
        String url = "jdbc:hive://localhost:10000/default";
        String user = "";
        String password = "";

        try (org.apache.hive.jdbc.HiveConnection conn = DriverManager.getConnection(url, user, password)) {
            // 创建表
            createTable(conn);

            // 插入数据
            insertData(conn);

            // 查询数据
            queryData(conn);
        }
    }

    private static void createTable(org.apache.hive.jdbc.HiveConnection conn) throws SQLException {
        String sql = "CREATE TABLE IF NOT EXISTS my_new_table (" +
                     "id INT," +
                     "name STRING" +
                     ") ROW FORMAT DELIMITED FIELDS TERMINATED BY ','";
        
        System.out.println("Creating table...");
        conn.createStatement().execute(sql);
        System.out.println("Table created successfully.");
    }

    private static void insertData(org.apache.hive.jdbc.HiveConnection conn) throws SQLException {
        String sql = "INSERT INTO TABLE my_new_table VALUES ('1', 'John Doe')";
        System.out.println("Inserting data...");
        conn.createStatement().execute(sql);
        System.out.println("Data inserted successfully.");

        sql = "INSERT INTO TABLE my_new_table VALUES ('2', 'Jane Smith')";
        conn.createStatement().execute(sql);
        System.out.println("Second row inserted successfully.");
    }

    private static void queryData(org.apache.hive.jdbc.HiveConnection conn) throws SQLException {
        String sql = "SELECT * FROM my_new_table";
        System.out.println("\nQuerying data...");
        java.sql.ResultSet rs = conn.createStatement().executeQuery(sql);

        while (rs.next()) {
            int id = rs.getInt(1);
            String name = rs.getString(2);
            System.out.printf("ID: %d, Name: %s%n", id, name);
        }
        System.out.println("Query completed.");
    }
}
